<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Http\Controllers;

use App\Services\UserService;
use App\Services\XcxService;
use Illuminate\Http\Request;

class XcxController extends Controller
{
    protected $xcxService;

    protected $userService;

    public function __construct(XcxService $xcxService, UserService $userService)
    {
        $this->xcxService = $xcxService;
        $this->userService = $userService;
    }

    public function xcxLogin(Request $request)
    {
        $jsCode = $request->input('code');
        $res = $this->xcxService->fetchCode2Session($jsCode);
        if (isset($res['error_code'])) {
            return renderSuccessJson($res['data'], $res['error_code']);
        }
        return renderSuccessJson($res);
    }

    public function xcxReg(Request $request)
    {
        $clientId = $request->input('client_id');
        $encryptedData = $request->input('encryptedData');
        $iv = $request->input('iv');
        $wxUserInfo = $this->xcxService->decryptUserInfoData($encryptedData, $iv, $clientId);
        $userId = $this->userService->xcxRegWithOutPhone($wxUserInfo);
        return renderSuccessJson([
            'user_id' => $userId,
        ]);
    }

    public function putUserPhone(Request $request)
    {
        $clientId = $request->input('client_id');
        $encryptedData = $request->input('encryptedData');
        $iv = $request->input('iv');
        $identity = $request->input('identity', 0);
        $userId = $request->input('user_id');
        $format = $this->xcxService->decryptUserPhoneData($encryptedData, $iv, $clientId);
        $login = $this->userService->savePhoneFromXcx($format, $userId, $identity);
        return renderSuccessJson($login);
    }
}
